#include "bflb_mtimer.h"
#include "bflb_uart.h"
#include "shell.h"
#include "board.h"
#include "bflb_gpio.h"

#include "rgb_light.h"
#include "button.h"

#define PIN_KEY GPIO_PIN_2

struct bflb_device_s* uart0;
struct bflb_device_s* gpio;

void uart_isr(int irq, void* arg)
{

    uint32_t intstatus = bflb_uart_get_intstatus(uart0);
    printf("intstatus: %d\n", intstatus);
    if (intstatus & UART_INTSTS_RX_FIFO) {
        while (bflb_uart_rxavailable(uart0)) {
            shell_handler(bflb_uart_getchar(uart0));
        }
    }
    if (intstatus & UART_INTSTS_RTO) {
        while (bflb_uart_rxavailable(uart0)) {
            shell_handler(bflb_uart_getchar(uart0));
        }
        bflb_uart_int_clear(uart0, UART_INTCLR_RTO);
    }

}
uint8_t old_data = 0;
uint8_t user_button_read(void) {
    return bflb_gpio_read(gpio, PIN_KEY);
}

void key_response_callback(void* argv)
{
    button_t* btn = (button_t*)argv;
    if (old_data != btn->_event) {
        old_data = btn->_event;
        printf("event: %d\n");
    }
    if (button_event_read(btn) == BTN_EVENT_PRESS_CLICK) {
        printf("event: down\n");
        rgb_toggle();
    }
}

int main(void)
{
    int ch;
    board_init();

    uart0 = bflb_device_get_by_name("uart0");
    printf("----------main---------------\n");
    bflb_uart_rxint_mask(uart0, false);
    bflb_irq_attach(uart0->irq_num, uart_isr, uart0);
    bflb_irq_enable(uart0->irq_num);
    shell_init();
    rgb_init();

    //板载key init
    gpio = bflb_device_get_by_name("gpio");
    bflb_gpio_init(gpio, PIN_KEY, GPIO_INPUT | GPIO_PULLDOWN);
    bflb_gpio_set(gpio, PIN_KEY);

    button_t key2;
    //读取gpio函数
    key2.usr_button_read = user_button_read;
    //事件回调函数
    key2.cb = key_response_callback;
    //点击时间间隔
    key2.click_hold_start_tick = FLEX_MS_TO_SCAN_CNT(100);

    button_register(&key2);
    while (1) {
        if ((ch = bflb_uart_getchar(uart0)) != -1) {
            shell_handler(ch);
        }
        //扫描GPIO状态
        button_scan();
        bflb_mtimer_delay_ms(10);
    }

}